package controller.addtextServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import com.google.gson.Gson; // 需要引入 Gson 库
import bean.Filesf;
import dao.util.FilesCreate;
import bean.User;

@WebServlet("/mynote/List")
public class ListServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 从 session 取当前用户
            User currentUser = null;
            if (request.getSession(false) != null) {
                currentUser = (User) request.getSession(false).getAttribute("user");
            }
            Integer userId = currentUser != null ? currentUser.getId() : null;

            FilesCreate filesCreate = new FilesCreate();
            List<Filesf> filesfs = (userId != null)
                    ? filesCreate.getMapperClass().listFilesByUserId(userId)
                    : filesCreate.getMapperClass().listFilesByUserId(-1); // 无用户则返回空/保护
            
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            
            if (filesfs != null) {
                Gson gson = new Gson();
                String json = gson.toJson(filesfs);
                out.print(json);
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"error\": \"获取文件列表失败\"}");
            }
            
            out.flush();
            filesCreate.closesession();
            out.close();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("{\"error\": \"服务器内部错误\", \"detail\": \"" + e.getMessage() + "\"}");
            out.flush();
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 为了向后兼容，保留 GET 方法处理
        doPost(request, response);
    }
}

